package com.yueke.gemini.utils;

import org.codehaus.jettison.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 说明：请求的公共类
 * Created by lenovo on 2016/12/18.
 */
public class RequestUtil {
    private static Logger logger = LoggerFactory.getLogger((RequestUtil.class));

    public static String getString(HttpServletRequest request) {
        String rv = null;
        InputStream inputStream = null;
        String charset = request.getCharacterEncoding();
        charset = charset == null ? "iso8859-1" : charset;
        try {
            inputStream = request.getInputStream();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            BufferedInputStream bis = null;
            byte[] buf = new byte[2048];
            bis = new BufferedInputStream(inputStream);
            for (int len = 0; (len = bis.read(buf)) != -1; ) {
                baos.write(buf, 0, len);
            }
            inputStream.close();
            rv = baos.toString(charset);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("params:" + rv);
        return rv;
    }

    public static boolean verifyCode(HttpServletRequest request, JSONObject jo) {
        if (jo == null) {
            return false;
        }
        String mobile = jo.optString("mobile");
        String verfycode = jo.optString("verifycode");
        HttpSession session = request.getSession();
        String smobile = String.valueOf(session.getAttribute("mobile"));
        String sverifycode = String.valueOf(session.getAttribute("verifycode"));

        logger.info("mobile前台：" + mobile);
        logger.info("mobile1：" + smobile);
        logger.info("verfycodee前台：" + verfycode);
        logger.info("sverifycode1：" + sverifycode);
        if (!mobile.equals(smobile) || !verfycode.equals(sverifycode)) {
            return false;
        }
        return true;
    }
}
